<template>
  <div class="container">
    <!-- 顶部搜索框 -->
    <div class="search">
      <navigator url="/pages/search/main" hover-class="none">
        <div class="input">
          <icon
            type="search"
            size="14"
          ></icon>
          <text>{{keyword}}</text>
        </div>
      </navigator>
    </div>
    <!-- tab切换 -->
    <div class="tab">
      <div
        class="tab-item"
        :class="{active: currentTab == index}"
        v-for="(item, index) in ['综合', '销量', '价格']"
        :key="index"
      >
        <text>{{item}}</text>
      </div>
    </div>
    <!-- 商品列表 -->
    <div class="wares">
      <div
        class="ware-item"
        v-for="(item,index) in goods"
        :key="index"
        @tap="handleToDetail(item.goods_id)"
      >
        <img
          :src="item.goods_small_logo"
          mode="aspectFill"
        />
        <div class="ware-info">
          <div class="ware-title">{{item.goods_name}}</div>
          <div class="ware-price colorRed">
            <text>￥</text>{{item.goods_price}}
          </div>
        </div>
      </div>
    </div>
    <div class="hasMore">
      <span v-if="hasMore">正在加载</span>
      <span v-else>没有更多</span>
    </div>
  </div>
</template>

<script>
  import request from "../../utils/request";
  export default {
    data() {
      return {
        goods: [],
        keyword: "",
        pagenum: 0,
        isLoading: false, //是否正在加载
        hasMore:true //是否有更多数据
      };
    },
    onLoad(query) {
      // 把关键字设置到data
      this.keyword = query.keyword;

      this.getGoods();
    },
    // 离开页面时执行；onUnload-》初始化data 
    onUnload(){
      // Object.assign合并对象，把后面的参数合并到第一个参数
      Object.assign(this,this.$options.data())
    },
    // 上拉触底加载
    onReachBottom() {
      this.getGoods();
    },
    methods: {
      // 跳转到商品详情页
      handleToDetail(id){
        wx.navigateTo({
          url:`/pages/goods_detail/main?goods_id=${id}`
        })
      },
      // 负责请求列表数据
      getGoods() {
        // 如果正在加载，直接返回
        if (this.isLoading || !this.hasMore) {
          return;
        }
        this.isLoading = true;
        // 只要触发上拉触底事件，页数加1
        this.pagenum = this.pagenum + 1;

        request
          .get("https://itjustfun.cn/api/public/v1/goods/search", {
            // url参数获取关键字
            query: this.keyword,
            pagenum: this.pagenum
          })
          .then(res => {
            const { goods } = res.data.data;
            // 转换商品的价格
            const newGoods = goods.map(item => {
              item.goods_price = Number(item.goods_price).toFixed(2);
              return item;
            });
            this.goods = this.goods.concat(newGoods);

            // 请求完成
            this.isLoading = false;
            // 是否有更多数据
            if(newGoods.length<20){
              this.hasMore = false;
            }
          });
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "style.scss";
</style>
